<template>
  <div class="dashboard-container">
    <div class="app-container">
      <div class="container">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>试题录入</span>
          </div>
          <el-form
            :model="form"
            ref="rulesform"
            label-width="80px"
            :rules="rules"
          >
            <!-- 学科 -->
            <el-form-item label="学科" prop="subjectID">
              <el-select
                placeholder="请选择"
                v-model="form.subjectID"
                @change="subjectChange"
              >
                <el-option
                  v-for="(item, index) in subjectList"
                  :key="index"
                  :label="item.subjectName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 目录 -->
            <el-form-item label="目录" prop="catalogID">
              <el-select placeholder="请选择目录" v-model="form.catalogID">
                <el-option
                  v-for="(item, index) in directorysList"
                  :key="index"
                  :label="item.directoryName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 企业 -->
            <el-form-item label="企业" prop="enterpriseID">
              <el-select placeholder="请选择企业" v-model="form.enterpriseID">
                <el-option
                  v-for="item in companysList"
                  :key="item.id"
                  :label="item.shortName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 城市 -->
            <el-row>
              <el-col :span="4">
                <el-form-item label="城市" prop="province">
                  <el-select
                    class="filter-item"
                    v-model="form.province"
                    @keyup.enter="handleFilter"
                    @change="handleProvince"
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in citySelect.province"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select> </el-form-item
              ></el-col>
              <el-col :span="3">
                <!-- 城市/ -->
                <el-form-item
                  label=""
                  :inline="true"
                  prop="city"
                  style="margin-left: -15px"
                >
                  <el-select
                    class="filter-item"
                    v-model="form.city"
                    @keyup.enter="handleFilter"
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in citySelect.cityDate"
                      :key="index"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 方向 -->
            <el-form-item label="方向" prop="direction">
              <el-select placeholder="获取方向" v-model="form.direction">
                <el-option
                  v-for="(item, index) in direction"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 题型 -->
            <el-form-item label="题型" prop="questionType">
              <el-radio-group v-model="form.questionType" @change="question">
                <el-radio label="1">单项</el-radio>
                <el-radio label="2">多选</el-radio>
                <el-radio label="3">简单</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 难度 -->
            <el-form-item label="难度" prop="difficulty">
              <el-radio-group v-model="form.difficulty">
                <el-radio label="1">简单</el-radio>
                <el-radio label="2">一般</el-radio>
                <el-radio label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 富文本编辑器(题干) -->
            <el-form-item label="题干" prop="question">
              <!-- 富文本内容 -->
              <quill-editor :options="editorOption" v-model="form.question"
              @click.native="onGoalClick1()" ref="editor1" />
            </el-form-item>
            <!-- 选择单项试题 -->
            <el-form-item
              label="选项"
              v-if="Checkbox === '1'"
              :key="this.form.questionType"
              prop="xz"
            >
              <el-radio-group v-model="xz" @change="checkChange">
                <div
                  v-for="item in form.options"
                  :key="item.code"
                  class="singleListTop"
                >
                  <el-radio :label="item.code"
                    >{{ item.code }}:
                    <el-input type="text" v-model="item.title" class="Input" />
                  </el-radio>
                  <br />
                </div> </el-radio-group
              ><br />
              <el-button
                type="danger"
                disabled
                icon="el-icon-plus"
                class="buttonquerstion"
                >增加选项与答案</el-button
              >
            </el-form-item>
            <!-- 选择多选试题 -->
            <el-form-item label="多选" v-if="Checkbox === '2'" :key="this.form.questionType">
              <el-checkbox-group v-model="checkList" @change="checkboxChange">
                <div
                  v-for="item in form.options"
                  :key="item.code"
                  class="singleListTop"
                >
                  <el-checkbox :label="item.code"
                    >{{ item.code + " :" }}
                    <el-input type="text" v-model="item.title" />
                  </el-checkbox>
                </div>
              </el-checkbox-group>
              <el-button
                type="danger"
                icon="el-icon-plus"
                @click="add"
                class="buttonquerstion"
                >增加选项与答案</el-button
              >
            </el-form-item>
            <!-- 视频解析 -->
            <el-form-item label="解析视频" style="width: 36%" prop="videoURL">
              <el-input v-model="form.videoURL"></el-input>
            </el-form-item>
            <!-- 富文本编辑器 -->
            <el-form-item label="答案解析" prop="answer">
              <!-- 富文本内容 -->
              <quill-editor :options="editorOption" v-model="form.answer" @click.native="onGoalClick2()" ref="editor2" />
            </el-form-item>
            <!-- 题目备注 -->
            <el-form-item label="题目备注" style="width: 36%" prop="remarks">
              <el-input type="textarea" v-model="form.remarks"></el-input>
            </el-form-item>
            <!-- 试题标签 -->
            <el-form-item label="试题标签" >
              <!-- allow-create// 输入文字创建新的条目 -->
              <!-- multiple是否多选 -->
              <el-select
                placeholder="请选择试题标签"
                v-model="form.tags"
                @focus="addtagsList"
                @change="inputChange"
                :multiple="true"
                allow-create
              >
                <el-option
                  v-for="item in tagList"
                  :key="item.id"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 确认提交 -->
            <el-form-item>
              <el-button type="primary" @click="addquestion"
                >确认提交</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { toolbarOptions, letterList, rules, optionsList } from './config'
// 学科列表
import { list } from '@/api/hmmm/subjects.js'
// 目录管理
import { list as directorysList } from '@/api/hmmm//directorys.js'
// 企业列表
import { list as companysList } from '@/api/hmmm/companys.js'
// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'
// 方向
import { direction } from '@/api/hmmm/constants.js'
// 试题标签
import { list as tagList } from '@/api/hmmm/tags.js'
// 添加试题// 数据回填
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      xz: '', // 单项
      checkList: [], // 选择框
      indexItem: 1, // 用于销毁组件
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 省
        city: '', // 城市
        direction: '', // 方向
        questionType: '1', // 选择
        difficulty: '1', // 难度
        question: '', // 文章内容
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ], // 试题
        videoURL: null || '', // 解析视频
        answer: '', // 答案解析
        remarks: null || '', // 解析试题
        tags: '' // 试题标签
      },
      /// 富文本
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      // 学科
      subjectList: [],
      id: '', // 学科要传的id(试题标签的id),
      directorysList: [], // 目录列表
      companysList: [], // 企业列表
      // 省市
      citySelect: {
        province: [],
        cityDate: []
      },
      Checkbox: '1', // 默认单项
      direction, // 获取方向
      letterList, // 字母表
      letter: '', // 字母
      numList: 4,
      tagList: '', // 试题标签
      tagvalue: [], // 试题选中的标签
      index: 1, //   // index多项选择
      // 数据回填
      data: {
        id: this.$route.query.aid
      },
      optionsList, // opation还原初始化状态
      rules // 正则校验
    }
  },
  async created () {
    const { data: res } = await list()
    this.subjectList = res.items
    // 企业列表
    const getcompanysList = await companysList()
    this.companysList = getcompanysList.data.items
    // 获取城市
    this.getCityData()
    // 数据回填模拟
    if (this.data.id) {
      this.getDataBackfill()
    }
  },
  methods: {
    // 数据回填
    async getDataBackfill () {
      // 数据回填进行修改
      const { data: res1 } = await detail(this.data)
      console.log(res1)
      // 1 处理回填处理目录
      // 从调用解决回填目录
      this.subjectChange(res1.subjectID)
      this.handleProvince(res1.province)
      // console.log(res1)
      if (res1.questionType === '1') {
        this.xz = res1.options.filter((item) => item.isRight === 1)[0].code
        console.log(this.xz)
      } else if (res1.questionType === '2') {
        this.checkList = res1.options
          .filter((item) => item.isRight === 1)
          .map((item) => item.code)
        this.Checkbox = '2'
      } else if (res1.questionType === '3') {
        this.Checkbox = '3'
      }
      // 转数组
      console.log(res1)
      const data = res1.tags.split(',')
      res1.tags = data
      this.form = { ...res1 }
    },
    // 1 学科管理(列表,目录要的id以及标签要的id)
    subjectChange (value) {
      this.form.catalogID = ''
      this.id = value
      this.getdirectorysList()
    },
    // 2  目录管理
    async getdirectorysList () {
      const { data: res } = await directorysList()
      const data = res.items.filter((item) => item.subjectID === this.id)
      this.directorysList = data
    },
    // 3  获取省
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 4 选省获取到市
    handleProvince (e) {
      this.citySelect.cityDate = citys(e)
      this.form.city = ''
    },
    // 5 选择框
    question (value) {
      this.Checkbox = value
      // 重置初始值
      if (this.Checkbox === '1') {
        this.form.questionType = '1'
        this.form.options = [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      } else if (this.Checkbox === '2') {
        this.form.questionType = '2'
        this.form.options = [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      } else {
        this.form.questionType = '3'
      }
    },
    // 6 动态添加选项与答案
    add () {
      this.letter = letterList[this.numList++]
      this.form.options.push({
        isRight: false,
        code: `${this.letter}`,
        title: '',
        img: ''
      })
      // this.counter.push(letterList[this.numList++])
    },
    // 9 试题标签
    async addtagsList () {
      const { data: res } = await tagList()
      const data = res.items.filter((item) => item.subjectID === this.id)
      // 利用学科管理率选试题标签
      // this.tagList = data
      this.tagList = data.map((item) => item.tagName)
      console.log(this.tagList)
    },
    // 10 添加试题
    addquestion () {
      this.$refs.rulesform.validate(async (valid) => {
        if (valid) {
          if (this.data.id) {
            console.log('修改')
            // this.form.tags = this.tagvalue.toString()
            this.form.tags = this.form.tags.join(',') || this.tagvalue.join(',')
            this.form.options = this.form.options.map(item => {
              if (item.isRight === 1) {
                item.isRight = true
              } else if (item.isRight === 0) {
                item.isRight = false
              }
              return item
            })
            console.log(this.form)
            try {
              await update(this.form)
              this.$message.success('修改成功')
              this.$router.push('/questions/list')
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log('添加')
            try {
              // 13 试题标签转字符串
              this.form.tags = this.tagvalue.join(',')
              // 如果tags为空就给一个默认值(后续处理解析视频以及解析试题默认值)
              if (this.form.tags === '') {
                this.form.tags = 'tags'
              }
              const data = await add(this.form)
              console.log(data)
              this.$message.success('添加成功')
              this.$router.push('/questions/list')
            } catch (error) {
              console.log('xxx')
            }
          }
        } else {
          return false
        }
      })
    },
    // 11 试题录入单项选择
    checkChange (value) {
      console.log(value)
      const index = this.form.options.findIndex((item) => item.code === value)
      this.form.options[index].isRight = true
      // this.form.options[index].title = this.title
    },
    // 12 多选提交
    checkboxChange (value) {
      this.index = value.length
      if (this.index === 1) {
        const index = this.form.options.findIndex(
          (item) => item.code === value[0]
        )
        this.form.options[index].isRight = true
      } else {
        const index = this.form.options.findIndex(
          (item) => item.code === value[this.index - 1]
        )
        this.form.options[index].isRight = true
      }
    },
    // 13 处理字符串
    inputChange (value) {
      this.tagvalue = value
    },
    // 富文本聚焦数据修改()
    onGoalClick1 () {
      this.$refs.editor1.quill.enable(true)
      this.$refs.editor1.quill.focus()
      this.goalInit = true
    },
    onGoalClick2 () {
      this.$refs.editor2.quill.enable(true)
      this.$refs.editor2.quill.focus()
      this.goalInit = true
    }
  },
  // 解决 富文本自动聚焦问题
  mounted () {
    // this.init()
    this.$refs.editor1.quill.enable(false)
    this.$refs.editor2.quill.enable(false)
  }
}
</script>

<style scoped lang="scss">
::v-deep .ql-editor {
  min-height: 200px;
}
.singleListTop {
  margin-top: 20px;
}
.buttonquerstion {
  margin: 20px 0px 10px 0px;
}
.el-select--medium {
  width: 32%;
}
.el-input--suffix {
  width: 32%;
}
//  城市样式
.filter-item {
  width: 185px;
  // padding: 0px 5px 0px 0px;
}
.cityClass {
  float: left;
}
</style>
